-module(file_common).
-export([process/4, process_stream/4, is_int_string/1]).

process(FileName, SortPred, IsDataLine, LineParser) ->
    {ok, Stream} = file:open(FileName, read),
    Line = io:get_line(Stream, ''), 
    ResultList = process_stream(Stream, Line, IsDataLine, LineParser),
    hd(lists:sort(SortPred, ResultList)).

process_stream(_Stream, eof, _IsDataLine, _LineParser)->
    [];
process_stream(Stream, Line, IsDataLine, LineParser) ->
    NextLine = io:get_line(Stream, ''),
    case IsDataLine(Line) of
        false ->
            process_stream(Stream, NextLine, IsDataLine, LineParser);
        true ->
            Result = LineParser(Line),
            [Result | process_stream(Stream, NextLine, IsDataLine, LineParser)]
    end.

%%is_int_string(Str) ->
%%    try list_to_integer(Str) of
%%        _Int -> true
%%    catch error:_ -> 
%%            false 
%%    end.

is_int_string(Str) ->
    {ok, IntRe} = re:compile("^\\d+$"),
    case re:run(Str, IntRe) of 
        {match, _Captured} -> true;
        nomatch -> false
    end.

